<template>
  <div>
    <div class="header">

      <div class="page-header">
        <el-page-header @back="goBack" content="角色管理">
        </el-page-header>
      </div>

      <el-button type="success" icon="el-icon-plus" @click="addData" size="small"
                 style="margin-top:10px;margin-left: 20px">新增角色
      </el-button>
      <div class="search">
        <el-input v-model="pageRequest.key" style="width: 200px;margin-right: 10px" placeholder="按角色名称查找"
                  size="small"></el-input>
        <el-button type="primary" icon="el-icon-search" size="small" @click="getRoleList">搜索</el-button>
      </div>
    </div>
    <el-card class="box-card"
             shadow="always">
      <template>
        <el-table
            :header-cell-style="{color:'#333',fontFamily:'MicrosoftYaHeiUI',fontSize:'14px',fontWeight:900}"
            size="mini"
            :data="roleList"
            style="width: 100%">
          <!--                    <el-table-column prop="roleId" label="角色ID" width="100"></el-table-column>-->
          <el-table-column prop="roleName" label="角色名称" width="100">

          </el-table-column>
          <el-table-column prop="roleKey" label="角色权限" width="130"></el-table-column>
          <el-table-column prop="status" :show-overflow-tooltip='true' width="100" label="角色状态">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium"
                        :type="scope.row.status === 0 ? 'success' : 'danger'">
                  {{ formatStatus(scope.row) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="createBy" width="100" label="创建人">

          </el-table-column>
          <el-table-column prop="createTime" width="140" label="创建时间"></el-table-column>
          <el-table-column prop="updateBy" width="120" label="更新人"></el-table-column>
          <el-table-column prop="updateTime" width="140" label="更新时间">

          </el-table-column>
          <el-table-column prop="remark" width="100" label="备注"></el-table-column>

          <el-table-column
              fixed="right"
              label="操作"
              width="200">
            <template slot-scope="scope">
              <el-button :disabled="scope.row.roleKey === 'system:role:admin'"
                         @click="grantData(scope.row)"
                         icon="el-icon-setting" type="text" size="mini">分配权限
              </el-button>

              <el-button :disabled="scope.row.roleKey === 'system:role:admin'"
                         @click="updateData(scope.row)"
                         icon="el-icon-edit" type="text" size="mini">编辑
              </el-button>
              <el-button :disabled="scope.row.roleKey === 'system:role:admin'"
                         @click="deleteData(scope.row.roleId)"
                         icon="el-icon-delete" type="text"
                         size="small">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <div class="block">
        <el-pagination
            style="float: right"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageRequest.pageNum"
            :page-sizes="[10, 50, 100, 200]"
            :page-size="pageRequest.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageResult.total">
        </el-pagination>
      </div>
    </el-card>
    <div>
      <el-dialog
          width="600px"
          top="3vh"
          :title="operate.title"
          :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="roleRules" ref="form" style="padding: 0px 50px" size="small">

          <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
            <el-input
                v-model="form.roleName"
                autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色权限标识" :label-width="formLabelWidth" prop="roleKey">
            <el-input
                v-model="form.roleKey"
                autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="角色状态" :label-width="formLabelWidth" prop="status">
            <el-switch
                v-model="form.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="启用"
                inactive-text="禁用"
                :active-value="0"
                :inactive-value="1">
            </el-switch>
          </el-form-item>

          <el-form-item label="备注" :label-width="formLabelWidth">
            <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入内容"
                v-model="form.remark">
            </el-input>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel" size="medium">取 消</el-button>
          <el-button type="primary" @click="operate.opType === 0?addRole('form'):updateRole('form')" size="medium">确 定
          </el-button>
        </div>
      </el-dialog>

      <el-dialog
          width="45%"
          top="3vh"
          title="权限分配"
          :visible.sync="dialogTreeVisible">
        <el-tree
            :data="menuAllList"
            show-checkbox
            :check-strictly="true"
            ref="tree"
            node-key="menuId"
            :default-expanded-keys="form.permissionList"
            :default-checked-keys="form.permissionList"
            @check="handleCheckNode"
            :props="defaultProps">
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelGrant" size="medium">取 消</el-button>
          <el-button type="primary" @click="grantPermission" size="medium">确 定
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import {addRole, deleteRole, getRoleList, grantPermission, updateRole} from "../../api/role";
import {mapActions} from "vuex";
import {getMenuAllList} from "../../api/menu";
import DeepCopyUtil from "@/utils/DeepCopyUtil";

export default {
  name: 'CourseManage.vue',
  components: {},
  data() {
    return {
      menuAllList: [],
      roleList: [],
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
        key: ''
      },
      pageResult: {
        total: 0,
        totalPage: 0,
        size: 0,
      },
      dialogFormVisible: false,
      dialogTreeVisible: false,
      formLabelWidth: '120px',
      operate: {
        opType: 0,
        title: ''
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      form: {},
      options: [
        {
          value: 0,
          label: '正常'
        }, {
          value: 1,
          label: '禁用'
        }
      ],
      sexOptions: [
        {
          value: '0',
          label: '男'
        }, {
          value: '1',
          label: '女'
        }
      ],
      roleRules: {
        roleName: [
          {required: true, message: '角色名称不能为空', trigger: 'blur'}
        ],
        roleKey: [
          {required: true, message: '角色权限标识不能为空', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '角色状态不能为空', trigger: 'change'}
        ],
      },
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    ...mapActions('tab', ['stepBack']),
    formatStatus(row) {
      return row.status === 0 ? '正常' : '禁用'
    },
    getMenuAllList() {
      getMenuAllList().then(res => {
        if (res.code === 200) {
          this.menuAllList = res.data
        }
      }).catch(err => {

      })
    },
    ...mapActions('menu', ['refreshMenu']),
    updateData(role) {
      this.dialogFormVisible = true;
      this.form = DeepCopyUtil.copy(role);
      this.operate.opType = 1
      this.operate.title = "编辑角色"
    },
    grantData(role) {
      this.dialogTreeVisible = true;
      this.form = role;
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
        this.$refs.tree.setCheckedKeys(role.permissionList);
      });

    },
    addData() {
      this.dialogFormVisible = true;
      this.form = {status: 0};
      this.operate.opType = 0
      this.operate.title = "新增角色"
    },
    deleteData(roleId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRole(roleId)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getRoleList() {
      getRoleList(this.pageRequest).then(res => {
        if (res.code === 200) {
          this.roleList = res.data.dataList
          this.pageResult.size = res.data.size
          this.pageResult.total = res.data.total
          this.pageResult.totalPage = res.data.totalPage
          if (res.data.size === 0 && res.data.pageNum > 1) {
            this.pageRequest.pageNum--;
            this.getRoleList();
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    deleteRole(roleId) {
      deleteRole({roleId}).then(res => {
        if (res.code === 200) {
          this.getRoleList()
          this.$message({
            message: '删除成功',
            type: 'success'
          });
        } else {
          this.$message({
            type: 'error',
            message: res.message,
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '删除失败!'
        });
      })
    },
    addRole(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addRole(this.form).then(res => {
            if (res.code === 200) {
              this.dialogFormVisible = false;
              this.getRoleList()
              this.$message({
                message: '新增成功',
                type: 'success'
              });
            } else {
              this.$message({
                type: 'error',
                message: '新增失败!'
              });
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: '新增失败!'
            });
          })
        } else {
          return false;
        }
      });
    },
    grantPermission() {
      grantPermission(this.form).then(res => {
        if (res.code === 200) {
          this.refreshMenu()
          this.getRoleList()
          this.$message({
            message: '权限分配成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: res.message,
            type: 'error'
          });
        }
        this.dialogTreeVisible = false;
      }).catch(err => {
        this.$message({
          message: '权限分配失败',
          type: 'error'
        });
        this.dialogTreeVisible = false;
      })
    },
    updateRole(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateRole(this.form).then(res => {
            if (res.code === 200) {
              this.dialogFormVisible = false;
              this.getRoleList()
              this.$message({
                message: '修改成功',
                type: 'success'
              });
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              });
            }
          }).catch(err => {
            this.$message({
              message: '更新失败',
              type: 'error'
            });
          })
        } else {
          return false;
        }
      });
    },
    handleCheckNode() {
      this.form.permissionList = this.$refs.tree.getCheckedKeys()
    },
    cancel() {
      this.dialogFormVisible = false;
      this.getRoleList();
    },
    cancelGrant() {
      this.dialogTreeVisible = false;
      this.getRoleList();
    },
    handleSizeChange(pageSize) {
      console.log(```每页 ${pageSize} 条`);
      this.pageRequest.pageSize = pageSize;
      this.getRoleList()
    },
    handleCurrentChange(pageNum) {
      console.log(`当前页: ${pageNum}`);
      this.pageRequest.pageNum = pageNum;
      this.getRoleList()
    },
    goBack() {
      window.history.back()
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getRoleList();
    this.getMenuAllList()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
  },
  beforeCreate() {
  },//生命周期 - 创建之前
  beforeMount() {
  }, //生命周期 - 挂载之前
  beforeUpdate() {
  }, //生命周期 - 更新之前
  updated() {
  }, //生命周期 - 更新之后
  beforeDestroy() {
  }, //生命周期 - 销毁之前
  destroyed() {
  }, //生命周期 - 销毁完成
  activated() {
  } //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style scoped>

.header {
  /*display: flex;*/
  /*!*垂直对齐*!*/
  /*align-items: center;*/
  height: 50px;
  background-color: #eff4f9;
}

.page-header {
  float: left;
  margin-top: 15px
}

.search {
  float: right;
  margin-top: 10px
}

.box-card {
  height: 100%;
  padding-bottom: 5px;
}

.block {
  margin-top: 5px;
}

.el-input, .el-textarea, .el-select {
  width: 260px
}

.el-form-item {
  width: 330px;
}


</style>
